/**
 * @description 地图编辑器
 * @author mirahs
 * @email 2892727493@qq.com
 */
export default class HtmlUtil {
    /**
     * 获取文件选择对话框
     * @param inputId 唯一 Id
     * @param accept 文件类型, 如: .json,.txt,image/jpeg,image/jpg,image/png
     * @param onchangeCb 选中文件时的回调
     * @returns html input 元素
     */
    public static getInputFile(inputId: string, accept: string = '', onchangeCb?: any): HTMLInputElement {
        let input = document.getElementById(inputId) as HTMLInputElement
        if (input) return input

        input = document.createElement('input') as HTMLInputElement
        input.id = inputId
        input.type = 'file'
        input.accept = accept
        input.style.display = 'none'
        if (onchangeCb) input.onchange = onchangeCb

        document.body.appendChild(input)

        return input
    }

    /**
     * 保存文件
     * @param filename 文件名
     * @param content 保存内容
     */
    public static saveFile(filename: string, content: any) {
        const downloadLink = document.createElement("a")
        downloadLink.download = filename
        downloadLink.innerHTML = "Save File"
        downloadLink.style.display = "none"

        const contentStr = JSON.stringify(content)
        const contentBlob = new Blob([contentStr])
        downloadLink.href = window.URL.createObjectURL(contentBlob)

        downloadLink.onclick = () => {
            document.body.removeChild(downloadLink)
        }

        document.body.appendChild(downloadLink)

        downloadLink.click()
    }

    public static openLink(url: string) {
        const downloadLink = document.createElement("a")
        downloadLink.setAttribute('href', url)
        downloadLink.setAttribute('target', '_blank')
        downloadLink.style.display = "none"

        downloadLink.onclick = () => {
            document.body.removeChild(downloadLink)
        }

        document.body.appendChild(downloadLink)

        downloadLink.click()
    }
}
